package service

import (
	"io"
	"log"
	"os"
)

type FileService struct {
}

func NewFileService() *FileService {
	return &FileService{}
}

func (service *FileService) SaveToLocal(file io.Reader, filename string) error {
	_, err := os.Stat("upload")
	if os.IsNotExist(err) {
		err = os.MkdirAll("upload", 0755)
		if err != nil {
			log.Println(err)
			return err
		}
	}
	f, err := os.OpenFile("./upload/"+filename, os.O_WRONLY|os.O_CREATE, 0755)
	if err != nil {
		log.Println(err)
		return err
	}
	defer f.Close()
	io.Copy(f, file)
	return nil
}

func (service *FileService) LoadFile(w io.Writer, filename string) error {
	f, err := os.Open("./upload/" + filename)
	if err != nil {
		log.Println(err)
		return err
	}
	defer f.Close()
	io.Copy(w, f)
	return nil
}
